﻿/*******************************************************
*类名称：WechatTokenManager
*版本号：V1.0.0.0
*作者：成俊杰
*CLR版本：4.0.30319.36264
*创建时间：2017-08-17 09:56:56
*说明：T_WechatToken管理类
*更新备注：
**********************************************************/

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Wechat.Dao;
using Wechat.Domain;
using Wechat.Util.JsonHelp;
using Wechat.Util.ParmsConfig;
using Wechat.Util.WechatUtil;

namespace Wechat.Manager.Implement
{
    /// <summary>
    /// T_WechatToken
    /// </summary>
    public class WechatTokenManager : GenericManagerBase<WechatToken>, IWechatTokenManager
    {
        public IWechatTokenRepository WechatTokenRepository { get; set; }
        /// <summary>
        /// 获取微信Token
        /// </summary>
        /// <returns></returns>
        public string GetAccessToken()
        {
            var data = WechatTokenRepository.GetAccessToken();
            if (data == null)
            {
                //说明token不存在或已过期，需要重新从微信服务器获取并保存在本地
                string response = WechatMsgUtil.PostData("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + ParmsConfigUtil.WechatAppId + "&secret=" + ParmsConfigUtil.WechatAppSecret, "");

                DataTable responseDT = JsonDataTable.JsonToDataTable(response);
                WechatToken token = new WechatToken()
                {
                    AccessToken = responseDT.Rows[0]["access_token"].ToString(),
                    TokenType = 0,
                    StartTime = DateTime.Now,
                    ExpiresTime = DateTime.Now.AddSeconds(double.Parse(responseDT.Rows[0]["expires_in"].ToString())),
                };
                var result = Insert(token);
                if (result > 0)
                {
                    return token.AccessToken;
                }
            }
            return data.AccessToken;
        }

    }
}